package com.cty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * @Auther: cty
 * @Date: 2020/4/17 18:07
 * @Description: NIO客户端
 * @version: 1.0
 */
public class NIOClient {
    public static void main(String[] args) {
        // 创建连接远程服务器的地址
        InetSocketAddress remote = new InetSocketAddress("localhost", 9999);
        SocketChannel socketChannel = null;
        Scanner scanner = new Scanner(System.in);

        // 定义缓存
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        try {
            // 开启通道
            socketChannel = SocketChannel.open();
            // 连接远程服务器
            boolean isConnected = socketChannel.connect(remote);
            System.out.println("isConnected: "+isConnected);

            while(true){
                System.out.println("Put message for sending to " + socketChannel.getRemoteAddress() + " server > ");
                String message = scanner.nextLine();  // 【阻塞方法】

                if(message.equals("exit")){
                    socketChannel.close();  // 关闭通道
                    System.out.println("Client exit.");
                    break;
                }

                // 将client控制台输入消息发送给server
                buffer.clear();
                buffer.put(message.getBytes("UTF-8"));
                buffer.flip();
                socketChannel.write(buffer);  // 【写操作】
                buffer.clear();

                // 读取server返回的消息
                System.out.println("Reading from " + socketChannel.getRemoteAddress() + " server: ");
                int readLength = socketChannel.read(buffer);  // 【读操作 等待数据和操作数据阶段都是阻塞的】
                if(readLength == -1){
                    break;
                }
                buffer.flip();
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);
                System.out.println(new String(bytes, "UTF-8"));
                buffer.clear();

            }

        } catch (IOException e) {
//            e.printStackTrace();
            try {
                System.out.println("Connection reset with " + socketChannel.getRemoteAddress() + " server.");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }finally {
            try {
                if(socketChannel!=null){
                    socketChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
